import { base64ToUrlSafe, hmacSha1, urlSafeBase64Encode } from "../utils.ts";
import { Mac } from "../auth/digest.ts";

interface PutPolicyOptions {
  scope: string;
}
export class PutPolicy {
  expires: number = 3600;
  scope: string;
  constructor(options: PutPolicyOptions) {
    this.scope = options.scope;
  }
  getFlags() {
    const flags: any = {};
    const attrs: string[] = [
      "scope",
      "isPrefixalScope",
      "insertOnly",
      "saveKey",
      "endUser",
      "returnUrl",
      "returnBody",
      "callbackUrl",
      "callbackHost",
      "callbackBody",
      "callbackBodyType",
      "callbackFetchKey",
      "persistentOps",
      "persistentNotifyUrl",
      "persistentPipeline",
      "fsizeLimit",
      "fsizeMin",
      "detectMime",
      "mimeLimit",
      "deleteAfterDays",
      "fileType",
    ];
    for (let i = attrs.length - 1; i >= 0; i--) {
      // @ts-ignore
      if (this[attrs[i]]) {
        // @ts-ignore
        flags[attrs[i]] = this[attrs[i]];
      }
    }
    flags.deadline = this.expires + Math.floor(Date.now() / 1000);
    return flags;
  }
  uploadToken(mac: Mac) {
    const flags = this.getFlags();
    const encodedFlags = urlSafeBase64Encode(JSON.stringify(flags));
    const encoded = hmacSha1(encodedFlags, mac.secretKey);
    const encodedSign = base64ToUrlSafe(encoded);
    return `${mac.accessKey}:${encodedSign}:${encodedFlags}`;
  }
}
